package com.gitee.stream;

import com.alibaba.fastjson.JSONObject;
import com.gitee.stream.cart.CartService;
import com.gitee.stream.cart.Sku;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 常见预定义收集器使用
 *
 * TODO 进入 Collectors 源码 中有更多的擦做
 * @author gcq
 * @Create 2022-07-02
 */
public class StreamCollector {

    /**
     * toList: 转换为一个集合
     */
    @Test
    public void toList() {
        List<Sku> cartSkuList = CartService.getCartSkuList();

        List<Sku> collect = cartSkuList.stream()
                .filter(sku -> sku.getTotalPrice() > 100)
                .collect(Collectors.toList());
        System.out.println(JSONObject.toJSONString(collect, true));
    }


    /**
     * Collectors.groupingBy: 基于对应元素进行分组，返回一个map
     */
    @Test
    public void groupTest() {
        List<Sku> list = CartService.getCartSkuList();

        // Map<分组条件，结果集合>
        Map<Object, List<Sku>> group = list.stream()
                .collect(Collectors.groupingBy(sku -> sku.getSkuCategory()));

        Set<Map.Entry<Object, List<Sku>>> entries = group.entrySet();
        entries.forEach(System.out::println);
        System.out.println(JSONObject.toJSONString(group, true));
    }

    /**
     * Collectors.partitioningBy: 基于对应条件进行分区
     */
    @Test
    public void partitionTest() {
        List<Sku> list = CartService.getCartSkuList();

        Map<Boolean, List<Sku>> partition = list.stream()
                .collect(Collectors.partitioningBy(sku -> sku.getTotalPrice() > 100));
        System.out.println(JSONObject.toJSONString(partition, true));
    }
}